package com.ssyc.student.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.CacheDataManager;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.ExitLoginUtil;
import com.ssyc.common.utils.NotificationsUtils;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.student.R;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

/**
 * 学生端--设置界面
 * Created by Administrator on 2018/5/17 0017.
 */
public class StudentSettingActivity extends BaseActivity implements View.OnClickListener, SwitchButton.OnCheckedChangeListener {

    private ImageView ivBack;
    private SwitchButton switchNoticeButton;
    //缓存大小的文本
    private TextView tvCachSize;
    private RelativeLayout llClean;
    private RelativeLayout llStrategy;
    private RelativeLayout llOut;
    private RelativeLayout rl_gywm;
    private RelativeLayout rl_zxzh;
    //隐私政策
    private RelativeLayout rl_yszc;
    //用户协议
    private RelativeLayout rl_yhxy;
    public static String FINISH = "StudentMainFinish";

    //头像
    private RoundedImageView ivHead;

    //姓名
    private TextView tvName;

    //账号
    private TextView tv_acc;

    //是否需要跳转的标识
    private boolean isNeeded = true;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_setting;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //设置默认的缓存大小
        initState();

        initData();
    }

    /**
     * 设置数据
     */
    private void initData() {
        ImageUtil.displayImage(this, ivHead, AccountUtils.getIcon(this), R.drawable.base_default_head);
        tvName.setText(AccountUtils.getName(this));
        tv_acc.setText(AccountUtils.getAccount(this));
    }

    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        switchNoticeButton = findViewById(R.id.switch_notice_button);
        tvCachSize = findViewById(R.id.tv_cach_size);
        llClean = findViewById(R.id.ll_clean);
        llClean.setOnClickListener(this);
        llStrategy = findViewById(R.id.ll_strategy);
        llStrategy.setOnClickListener(this);
        llOut = findViewById(R.id.ll_out);
        llOut.setOnClickListener(this);
        rl_zxzh = findViewById(R.id.rl_zxzh);
        rl_zxzh.setOnClickListener(this);


        ivHead = findViewById(R.id.iv_head);
        tvName = findViewById(R.id.tv_name);
        tv_acc = findViewById(R.id.tv_acc);

        rl_gywm = findViewById(R.id.rl_gywm);
        rl_gywm.setOnClickListener(this);

        rl_yszc = findViewById(R.id.rl_yszc);
        rl_yszc.setOnClickListener(this);

        rl_yhxy = findViewById(R.id.rl_yhxy);
        rl_yhxy.setOnClickListener(this);

    }


    /**
     * 设置初始状态
     */
    private void initState() {

        //设置显示缓存大小的TextView
        try {
            if ("0.0B".equals(CacheDataManager.getTotalCacheSize(StudentSettingActivity.this))) {
                tvCachSize.setText("(0.00M)");
            } else {
                tvCachSize.setText("(" + CacheDataManager.getTotalCacheSize(this) + ")");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        switchNoticeButton.setOnCheckedChangeListener(this);
    }

    /**
     * 开关按钮的监听事件
     *
     * @param view
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {

        //点关闭时,这个时候通知状态是true,开关状态是false   切回来的时候通知状态还是true,开关状态同步为true
        if (isChecked == NotificationsUtils.isOpenNotification(this)) {
            isNeeded = false;
        } else {
            isNeeded = true;
        }

        if (isNeeded) {
            //需要跳转界面
            NotificationsUtils.startSysSettingActivity(this);
        }
    }

    /**
     * 同步通知开关的状态
     */
    private void sycSwitchState() {
        if (NotificationsUtils.isOpenNotification(this)) {
            //开启了通知权限
            switchNoticeButton.setChecked(true);
        } else {
            switchNoticeButton.setChecked(false);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        sycSwitchState();
    }

    /**
     * 弹出清除缓存的弹框
     */
    private void showCleanPop() {
        try {
            if ("0.0B".equals(CacheDataManager.getTotalCacheSize(getApplicationContext()))) {
                //证明无缓存需要清理
                UIHelper.showToast(this, "暂无缓存需要清理");
                return;
            } else {

//                AlertDialogUtil.showAlertDialog(true, this, "确定清除所有本地缓存吗?", new AlertDialogUtil.onListener() {
//                    @Override
//                    public void onClickOk() {
//                        //清除缓存
//                        cleanCache();
//                    }
//
//                    @Override
//                    public void onClickDismiss() {
//
//                    }
//                });
                //弹框
                PopUpManager.showPop(StudentSettingActivity.this, R.layout.st_pop_clean_cach, 0.3f, StudentSettingActivity.this, new PopUpManager.onGetViewListener() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                        //关闭按钮
                        ImageView ivClose = view.findViewById(R.id.lv_close);
                        Button btCommit = view.findViewById(R.id.bt_commit);
                        ivClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //关闭弹框
                                PopUpManager.dismiss();
                            }
                        });
                        btCommit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //清除缓存
                                cleanCache();
                                //关闭弹框
                                PopUpManager.dismiss();
                            }
                        });
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出退出登录的弹框
     */
    private void showExitPop() {

        //弹框
        PopUpManager.showPopByMatchParent(StudentSettingActivity.this, R.layout.base_pop_exit_sys, 0.3f, StudentSettingActivity.this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                TextView tv_again = view.findViewById(R.id.tv_again);
                TextView tv_over = view.findViewById(R.id.tv_over);
                tv_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //取消
                            PopUpManager.dismiss();
                        }

                    }
                });

                tv_over.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //退出学生端的相关操作,清空SP的相关数据
                            ExitLoginUtil.exitLogin(StudentSettingActivity.this);

                            //通知首页关闭
                            EventBus.getDefault().post(new BusInfo(FINISH));

                            finish();
                            //关闭弹框
                            PopUpManager.dismiss();
                        }

                    }
                });
            }
        });
    }


    /**
     * 注销用户的操作
     */
    private void doAnsubscribeAction() {
        PopUpManager.showPopByMatchParent(this, R.layout.com_pop_unsubscribe, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {

            }
        });
    }


    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        if (!isDoubleClick(v)) {
            int id = v.getId();
            if (id == R.id.iv_back) {
                //返回
                finish();
            } else if (id == R.id.ll_clean) {
                //清除缓存
//                showCleanPop();
                showCleanCachePop();
            } else if (id == R.id.ll_strategy) {
                //攻略
                ARouter.getInstance().build("/teacher/TeacherStrategyActivity").navigation();
            } else if (id == R.id.ll_out) {
                //退出登录
                showExitPop();

            } else if (id == R.id.rl_gywm) {
                //关于我们
                ARouter.getInstance().build("/main/AboutUsActivity").navigation();
            } else if (id == R.id.rl_zxzh) {
                //注销用户
                doAnsubscribeAction();
            } else if (id == R.id.rl_yszc) {
                //隐私政策
                ARouter.getInstance().build("/main/AgreementAndPrivacyActivity").withString("title", "隐私政策").navigation();
            } else if (id == R.id.rl_yhxy) {
                //用户协议
                ARouter.getInstance().build("/main/AgreementAndPrivacyActivity").withString("title", "用户协议").navigation();
            }

        }
    }


    /**
     * 清除缓存的方法
     */
    private void cleanCache() {
        new Thread(new clearCache()).start();
    }


    /**
     * 处理清除缓存消息的Handler对象
     */
    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:

                    UIHelper.showToast(StudentSettingActivity.this, "清除缓存成功");

                    try {
                        if ("0.0B".equals(CacheDataManager.getTotalCacheSize(StudentSettingActivity.this))) {
                            tvCachSize.setText("(0.00M)");
                        } else {
                            tvCachSize.setText("( " + CacheDataManager.getTotalCacheSize(StudentSettingActivity.this) + " )");

                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    }

                    break;
            }
        }
    };


    /**
     * 实现清除缓存的Runnable
     */
    class clearCache implements Runnable {

        @Override

        public void run() {

            try {

                CacheDataManager.clearAllCache(StudentSettingActivity.this);

                Thread.sleep(300);

                if (CacheDataManager.getTotalCacheSize(StudentSettingActivity.this).startsWith("0")) {

                    handler.sendEmptyMessage(0);

                }

            } catch (Exception e) {

                return;

            }

        }

    }


    /**
     * 清除缓存
     */
    private void showCleanCachePop() {
        PopUpManager.showPopByMatchParent(this, R.layout.base_pop_clean_caches, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                TextView tv_again = view.findViewById(R.id.tv_again);
                TextView tv_over = view.findViewById(R.id.tv_over);
                tv_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //取消
                            PopUpManager.dismiss();
                        }

                    }
                });

                tv_over.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //确定
                            PopUpManager.dismiss();
                            //清除缓存
                            cleanCache();
                        }

                    }
                });

            }
        });
    }


    @Override
    public void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

}
